'use strict';

import Base from './base.js';

var fs = require('fs');
var path = require('path');


export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */

  init(http) {
    super.init(http);
  }

  //后台主界面
  async loginAction() {
    return this.display("public/login_v2");
  }

  //检测登入
  async dologinAction() {
    let data = this.post();
    if (this.isAjax('post')) { //异步请求才处理
      if (data.username == '') {
        this.fail(2, '用户名不能为空!');
      }
      if (data.password == '') {
        this.fail(2, '密码不能为空!');
      }
      let admin = await this.model('admin').login(data.username, data.password);
      if (!think.isEmpty(admin)) {
        await this.session('admin', admin);
        this.success({ url: '/admin/index' }, '登录成功');
      } else {
        this.fail(2, '帐号或密码错误');
      }
    } else {
      return think.statusAction(404, this.http);
    }

  }

  //上传图片
  async uploadimgAction() {
    //这里的 key 需要和 form 表单里的 name 值保持一致
    var file = think.extend({}, this.file('imgFile'));
    
   
    //过大不允许上传
    if(file.size > this.config('max_upload')){
       var returnData = {error:1,message:'上传失败，图片过大'};
       this.end(returnData);
    }

     //获取判断是否图片
    if(!isImg(file.originalFilename)){
       var returnData = {error:1,message:'只能上传'+this.config('img_type')+'的图片'};
       this.end(returnData);
    }

    
    var filepath = file.path;

    //文件上传后，需要将文件移动到项目其他地方，否则会在请求结束时删除掉该文件
    var basePath =  this.config('publich_path')+'upload/editor/'+dateformat('yyyymmdd',new Date())+'/';
    var uploadPath = think.RESOURCE_PATH +basePath;
    think.mkdir(uploadPath);
    var basename = path.basename(filepath);
    //var basename = think.md5(filepath);
    fs.renameSync(filepath, uploadPath + '/' + basename);
    file.path = uploadPath + '/' + basename;
    if (think.isFile(file.path)) {
      var url = basePath+basename;
      var returnData = {error:0,url:url};
      this.end(returnData);
      //this.end('is file')
    } else {
       var returnData = {error:1,message:'上传失败，可能图片过大或格式问题'};
       this.end(returnData);
      //this.end('not exist')
    }
  }
}